package priv.conceit.sc.hoxton.common.web.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import priv.conceit.sc.hoxton.common.web.WebResponse;
import priv.conceit.sc.hoxton.common.web.exception.WebExceptionEnum;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author Conceit
 * @since 1.0.0, 2020/10/20
 */
@Component
@Slf4j
public class WebAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

		WebResponse restfulResponse = new WebResponse();
		restfulResponse.setStateCode(WebExceptionEnum.EX_USER_AUTH_FAILURE.getKey());
		restfulResponse.setMessage(WebExceptionEnum.EX_USER_AUTH_FAILURE.getValue());

		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(restfulResponse);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json);
	}
}
